package com.alingrad.iou;

import java.io.InputStream;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.FilterQueryProvider;
import android.widget.QuickContactBadge;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

public class PersonActivity extends ListActivity {
	public static final String KEY_ID = "_id";
	
	private ContentResolver mCr;
	private IOUDbAdapter mDb;
	private long mId;
	
	private long mContactId;
	
	private static final int DIALOG_LINK_CONTACT_ID = 0;
	private static final int DIALOG_ERROR_NO_CONTACT = 1;
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_LINK_CONTACT_ID:
			mContactId = -1;
			Dialog linkContactDialog = new Dialog(this);
			linkContactDialog.setTitle(R.string.dialog_link_contact_title);
			linkContactDialog.setContentView(R.layout.dialog_link_contact);
			final Button linkContactOkayButton = (Button)linkContactDialog.findViewById(R.id.dialog_link_contact_okay_button);
			final Button linkContactCancelButton = (Button)linkContactDialog.findViewById(R.id.dialog_link_contact_cancel_button);
			
			OnClickListener linkContactDialogClickListener = new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (v == linkContactOkayButton)
						onLinkContactOkayButtonPressed();
					else
						dismissDialog(DIALOG_LINK_CONTACT_ID);
				}
			};
			
			linkContactOkayButton.setOnClickListener(linkContactDialogClickListener);
			linkContactCancelButton.setOnClickListener(linkContactDialogClickListener);
			
			final AutoCompleteTextView contactEditor = (AutoCompleteTextView)linkContactDialog.findViewById(R.id.dialog_link_contact_editor);
			contactEditor.setAdapter(getContactAdapter());
			contactEditor.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					mContactId = -1;
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
				}
				
				@Override
				public void afterTextChanged(Editable s) {
				}
			});
			contactEditor.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position,
						long id) {
					mContactId = id;
				}
			});
			
			return linkContactDialog;
		case DIALOG_ERROR_NO_CONTACT:
			AlertDialog.Builder b = new AlertDialog.Builder(this);
			AlertDialog d = b.create();
			d.setTitle(R.string.error_dialog_label);
			d.setMessage(getResources().getString(R.string.error_link_contact_fields_message));
			d.setButton(getResources().getString(R.string.okay), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			return d;
		}
		return super.onCreateDialog(id);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.person);
		mCr = getContentResolver();
		
		mId = getIntent().getLongExtra(KEY_ID, -1);
		
		mDb = new IOUDbAdapter(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.person_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.person_menu_add_transaction:
			onAddTransactionButtonPressed();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void onAddTransactionButtonPressed() {
		Intent i = new Intent(this, NewTransactionActivity.class);
		i.setAction(NewTransactionActivity.ACTION_NEW_WITH_PERSON);
		i.putExtra(NewTransactionActivity.KEY_PERSON_ID, mId);
		startActivity(i);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mDb.open();
		fillData();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mDb.close();
	}

	private void fillData() {
		if (mId != -1) {
			final QuickContactBadge contactBadge = 
				(QuickContactBadge) findViewById(R.id.person_title_bar_contact_badge);
			final TextView contactName = 
				(TextView) findViewById(R.id.person_title_bar_contact_name);
			final TextView contactBalance =
				(TextView) findViewById(R.id.person_title_bar_contact_balance);
			
			Cursor person = mDb.getPerson(mId);
			person.moveToFirst();
			final long contactId = person.getLong(person.getColumnIndex(
					IOUDbAdapter.KEY_PEOPLE_CONTACT_ID));
			
			OnClickListener badgeClickListener = new OnClickListener() {
				@Override
				public void onClick(View v) {
					onBadgeClicked();
				}
			};
			
			if (contactId == -1) {
				contactName.setText(person.getString(
						person.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_NAME)));
				contactBadge.setImageResource(R.drawable.ic_contact_picture);
				contactBadge.setOnClickListener(badgeClickListener);
			} else {
				final Uri contactUri = ContentUris.withAppendedId(
						ContactsContract.Contacts.CONTENT_URI, contactId);
				contactBadge.assignContactUri(contactUri);
				Cursor contact = mCr.query(ContactsContract.Contacts.CONTENT_URI,
						new String[] {ContactsContract.Contacts.DISPLAY_NAME},
						ContactsContract.Contacts._ID + " = " + contactId, 
						null, null);
				
				if (contact == null || contact.getCount() <= 0) {
					mDb.unlinkPerson(mId);
					contactBadge.setImageResource(R.drawable.ic_contact_picture);
					contactName.setText(person.getString(
							person.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_NAME)));
					contactBadge.setOnClickListener(badgeClickListener);
				} else {
					contact.moveToFirst();
					InputStream is = ContactsContract.Contacts.
							openContactPhotoInputStream(mCr, contactUri);
					if (is == null)
						contactBadge.setImageResource(R.drawable.ic_contact_picture);
					else
						contactBadge.setImageBitmap(BitmapFactory.decodeStream(is));
					contactName.setText(contact.getString(contact.getColumnIndex(
							ContactsContract.Contacts.DISPLAY_NAME)));
				}
				contact.close();
			}
			
			float bal = person.getFloat(
					person.getColumnIndex(IOUDbAdapter.KEY_PEOPLE_BALANCE));
			
			if (bal < 0) {
				bal *= -1;
				contactBalance.setTextColor(Color.RED);
			} else
				contactBalance.setTextColor(Color.GREEN);
			
			contactBalance.setText("$" + bal);
			person.close();
			
			Cursor c = mDb.getTransactionsOfPerson(mId);
			startManagingCursor(c);
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.person_transaction_list_row, c,
					new String[] {IOUDbAdapter.KEY_TRANSACTION_DATE, IOUDbAdapter.KEY_TRANSACTION_AMOUNT},
					new int[] {R.id.person_list_row_date, R.id.person_list_row_amount});
			adapter.setViewBinder(new ViewBinder() {
				@Override
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
					if (view.getId() == R.id.person_list_row_amount) {
						float amt = cursor.getFloat(columnIndex);
						if (amt < 0) {
							amt *= -1;
							((TextView) view).setTextColor(Color.RED);
						} else
							((TextView) view).setTextColor(Color.GREEN);
						((TextView) view).setText("$" + amt);
						return true;
					}
					return false;
				}
			});
			setListAdapter(adapter);
		}	
	}
	
	private SimpleCursorAdapter getContactAdapter() {
		Cursor c = mCr.query(ContactsContract.Contacts.CONTENT_URI, 
				new String[] {Contacts.DISPLAY_NAME, Contacts._ID}, null, null, null);
		final SimpleCursorAdapter retval = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, c, new String[] {
				Contacts.DISPLAY_NAME}, new int[] {android.R.id.text1});
		retval.setCursorToStringConverter(new CursorToStringConverter() {
			@Override
			public CharSequence convertToString(Cursor cursor) {
				return cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
			}
		});
		retval.setFilterQueryProvider(new FilterQueryProvider() {
			@Override
			public Cursor runQuery(CharSequence constraint) {
				return mCr.query(Contacts.CONTENT_URI, 
						new String[] { Contacts.DISPLAY_NAME, 
						Contacts._ID}, 
						Contacts.DISPLAY_NAME + " LIKE '%" + constraint + "%'", 
						null, 
						null);
			}
		});
		return retval;
	}
	
	private void onLinkContactOkayButtonPressed() {
		if (mContactId != -1) {
			mDb.linkPerson(mId, mContactId);
			fillData();
			dismissDialog(DIALOG_LINK_CONTACT_ID);
		} else {
			showDialog(DIALOG_ERROR_NO_CONTACT);
		}
	}
	
	private void onBadgeClicked() {
		showDialog(DIALOG_LINK_CONTACT_ID);
	}
}
